<template>
  <div class="role-container">
    <div class="role-header">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增角色
      </el-button>
    </div>

    <div class="role-content">
      <el-table :data="roleList" style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" min-width="180" />
        <el-table-column prop="roleCode" label="角色编码" width="180" />
        <el-table-column prop="description" label="角色描述" min-width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
              {{ row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="handlePermission(row)">
              权限设置
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="row.roleCode === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input 
            v-model="formData.roleCode" 
            placeholder="请输入角色编码"
            :disabled="formType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            active-value="enabled"
            inactive-value="disabled"
            :disabled="formData.roleCode === 'admin'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionVisible"
      title="权限设置"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-tree
        ref="treeRef"
        :data="menuList"
        show-checkbox
        node-key="id"
        :props="{ label: 'title' }"
        :default-checked-keys="selectedPermissions"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermission">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 角色列表数据
const roleList = ref([
  {
    id: 1,
    roleName: '超级管理员',
    roleCode: 'admin',
    description: '系统超级管理员',
    createTime: '2024-01-01 00:00:00',
    status: 'enabled'
  },
  {
    id: 2,
    roleName: '普通用户',
    roleCode: 'user',
    description: '普通用户角色',
    createTime: '2024-01-01 00:00:00',
    status: 'enabled'
  }
])

// 菜单列表数据
const menuList = ref([
  {
    id: 1,
    title: '控制台',
    children: []
  },
  {
    id: 2,
    title: '系统管理',
    children: [
      {
        id: 21,
        title: '用户管理'
      },
      {
        id: 22,
        title: '角色管理'
      },
      {
        id: 23,
        title: '菜单管理'
      }
    ]
  }
])

// 表单相关
const dialogVisible = ref(false)
const formType = ref('add')
const formRef = ref(null)
const formData = ref({
  roleName: '',
  roleCode: '',
  description: '',
  status: 'enabled'
})

// 表单校验规则
const formRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '角色编码只能包含小写字母、数字和下划线，且必须以字母开头', trigger: 'blur' }
  ]
}

// 权限设置相关
const permissionVisible = ref(false)
const treeRef = ref(null)
const selectedPermissions = ref([])
const currentRole = ref(null)

// 新增角色
const handleAdd = () => {
  formType.value = 'add'
  formData.value = {
    roleName: '',
    roleCode: '',
    description: '',
    status: 'enabled'
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  formType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除角色
const handleDelete = (row) => {
  if (row.roleCode === 'admin') {
    ElMessage.warning('超级管理员角色不能删除')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除该角色吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
  })
}

// 打开权限设置
const handlePermission = (row) => {
  currentRole.value = row
  // TODO: 获取角色权限
  selectedPermissions.value = [1, 21] // 模拟已有权限
  permissionVisible.value = true
}

// 保存权限设置
const handleSavePermission = () => {
  const checkedKeys = treeRef.value.getCheckedKeys()
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
  const permissions = [...checkedKeys, ...halfCheckedKeys]
  
  // TODO: 调用保存权限接口
  console.log('保存权限:', permissions)
  ElMessage.success('保存成功')
  permissionVisible.value = false
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // TODO: 调用保存接口
      ElMessage.success(formType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.role-header {
  margin-bottom: 20px;
}

.role-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

:deep(.el-tree) {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-tree-node__content) {
  height: 32px;
}
</style> 